package com.zmn.plat.admin.controller.product.relation;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.zmn.plat.business.interfaces.servcategory.ShowCategoryAssociationBService;
import com.zmn.plat.common.constant.ProductConsts;
import com.zmn.plat.model.entity.category.BaseCategory;
import com.zmn.plat.model.entity.category.BaseCategoryQuery;
import com.zmn.plat.model.entity.product.ServProduct;
import com.zmn.plat.model.entity.product.ServProductQuery;
import com.zmn.plat.model.entity.product.ServProductRelation;
import com.zmn.plat.model.entity.product.ServProductRelationQuery;
import com.zmn.plat.model.entity.servcategory.ShowCategoryAssociationVO;
import com.zmn.plat.model.vo.product.relation.ServProductRelationVO;
import com.zmn.plat.services.interfaces.category.BaseCategoryService;
import com.zmn.plat.services.interfaces.product.ServProductRelationService;
import com.zmn.plat.services.interfaces.product.ServProductService;

/**
 * @author tanbiao
 * @description:产品关联
 * @since 2019/9/20 11:12
 * @modifier
 **/
@Controller
@RequestMapping("/showProduct/relation/")
public class ServProductRelationListController {
    private Logger logger = LoggerFactory.getLogger(ServProductRelationListController.class);
    @Resource
    ServProductRelationService productRelationService;
    @Resource
    ServProductService servProductService;
    @Resource
    BaseCategoryService baseCategoryService;
    @Resource
    ShowCategoryAssociationBService showCategoryAssociationBService;

    /**
     * 功能描述:关联后台产品列表
     *
     * @param query
     * @return org.springframework.web.servlet.ModelAndView
     * @author tanbiao
     * @since 2019/9/20
     * @modifier
     */
    @RequestMapping(value = "list")
    @RequiresPermissions("/showProduct/relation/list.action")
    public ModelAndView list(@ModelAttribute ServProductRelationQuery query) {
        ModelAndView mav = new ModelAndView("product/show/relation/list");
        try {
            ServProduct servProductVO = servProductService.findByKey(query.getShowProductId());
            List<ServProductRelationVO> items = productRelationService.listByQueryForShow(query);
            mav.addObject("items", items);
            mav.addObject("flag", 6);
            mav.addObject("servProductVO", servProductVO);
            mav.addObject("productName", servProductVO.getName());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return mav;
    }

    /**
     * 功能描述 :关联关系跳转页面
     *
     * @param query
     * @return org.springframework.web.servlet.ModelAndView
     * @author tanbiao
     * @since 2019/10/15
     * @modifier
     */
    @RequestMapping(value = "addEditView")
    @RequiresPermissions("/showProduct/relation/addEditView.action")
    public ModelAndView addEdit(@ModelAttribute ServProductRelationQuery query) {
        ModelAndView mav = new ModelAndView("product/show/relation/addEdit");
        try {
            // 当前产品名称
            ServProduct servProductVO = servProductService.findByKey(query.getShowProductId());
            List<ShowCategoryAssociationVO> showCategoryAssociationVOS = showCategoryAssociationBService
                .listByShowCategoryId(servProductVO.getServCategId(), servProductVO.getCategOneId(), servProductVO.getCategId());
            ServProductQuery servProductQuery = new ServProductQuery();
            List<ServProduct> products = new ArrayList<>();
            List<BaseCategory> categTwos = new ArrayList<>();
            Map<Integer, List<ServProduct>> map = new HashMap<>();
            List<Integer> categIds = new ArrayList<>();
            if (!CollectionUtils.isEmpty(showCategoryAssociationVOS)) {
                List<Integer> categOneIds = new ArrayList<>();
                showCategoryAssociationVOS.forEach(e -> {
                    if (!categOneIds.contains(e.getCategOneId())) {
                        categOneIds.add(e.getCategOneId());
                    }
                    if (!categIds.contains(e.getCategId())) {
                        categIds.add(e.getCategId());
                    }
                });
                servProductQuery.setServCategId(servProductVO.getServCategId());
                servProductQuery.setCategOneIds(CollectionUtils.isEmpty(categOneIds) ? null : categOneIds);
                servProductQuery.setCategIds(CollectionUtils.isEmpty(categIds) ? null : categIds);
                // servProductQuery.setServCategId(servProductVO.getServCategId());
                servProductQuery.setShowType(ProductConsts.ERP_PRODUCT_TYPE);
                // 后台产品
                products = servProductService.listByQuery(servProductQuery);
                ServProductRelationQuery relationQuery = new ServProductRelationQuery();
                relationQuery.setShowProductId(query.getShowProductId());
                List<ServProductRelation> servProductRelations = productRelationService.listByQuery(relationQuery);
                if (!CollectionUtils.isEmpty(servProductRelations)) {
                    List<Integer> relationedProductIds =
                        servProductRelations.stream().map(e -> e.getProductId()).collect(Collectors.toList());
                    products = products.stream().filter(e -> !relationedProductIds.contains(e.getProductId())).collect(Collectors.toList());
                }
                // 按照二级分类显示
                map = products.stream().collect(Collectors.groupingBy(ServProduct::getCategId));
                // 二级分类名称
                BaseCategoryQuery baseCategoryQuery = new BaseCategoryQuery();
                baseCategoryQuery.setShowType(ProductConsts.ERP_PRODUCT_TYPE);
                categTwos = baseCategoryService.findByKeys(categIds);

            }

            // 已存在的关联关系
            List<ServProductRelationVO> items = productRelationService.listByQueryForShow(query);
            StringBuilder stringBuilder = new StringBuilder();
            // 已存在关联关系的Id
            items.stream().forEach(e -> stringBuilder.append(e.getProductId()).append(","));
            mav.addObject("productName", servProductVO.getName());
            mav.addObject("products", products);
            mav.addObject("selected", stringBuilder);
            mav.addObject("servProductVO", servProductVO);
            mav.addObject("categTwos", categTwos);
            mav.addObject("map", map);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return mav;
    }
}
